<template>
  <div class="form-section">
    <h3>{{ formData.id ? '编辑系统' : '新增系统' }}</h3>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <div class="form-row">
        <div class="form-item">
          <el-form-item label="系统编码" prop="systemCode">
            <el-input
              v-model="formData.systemCode"
              :disabled="!!formData.id"
              placeholder="请输入系统编码"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="系统名称" prop="systemName">
            <el-input
              v-model="formData.systemName"
              placeholder="请输入系统名称"
              maxlength="6"
              show-word-limit
            />
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="系统标签" prop="systemTag">
            <el-radio-group v-model="formData.systemTag">
              <el-radio
                v-for="tag in options.systemTags"
                :key="tag.value"
                :label="tag.value"
              >
                {{ tag.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="formData.sort"
              placeholder="请输入排序"
              maxlength="4"
            />
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="是否外链" prop="isExternal">
            <el-radio-group v-model="formData.isExternal">
              <el-radio
                v-for="option in options.yesNoOptions"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="显示状态" prop="displayStatus">
            <el-radio-group v-model="formData.displayStatus">
              <el-radio
                v-for="status in options.displayStatusOptions"
                :key="status.value"
                :label="status.value"
              >
                {{ status.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="form-item full-width">
            <input type="file" @change="handleFileUpload" :disabled="uploading" />
            <div v-if="uploadProgress > 0">上传进度: {{ uploadProgress }}%</div>

            <a style="font-size: 12px;" v-if="formData.icon" :href="formData.icon" target="_blank">查看图标</a>
        </div>
        <div class="form-item full-width">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              maxlength="150"
              show-word-limit
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import type { SystemForm as SystemFormType } from '@/types/system';
import { fileApi } from '@/api/user'

interface Props {
  formData: SystemFormType;
}

interface Emits {
  (e: 'submit', data: SystemFormType): void;
  (e: 'reset'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const uploading = ref(false)
const uploadProgress = ref(0)

// 处理文件上传
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) return

  const file = target.files[0]
  if (!file) return // 增加此判断防止 file 为 undefined

  uploading.value = true
  uploadProgress.value = 0

  try {
    const response = await fileApi.upload(file, (progress) => {
      console.log('上传进度:', progress)
    })
    if (response.code === 200) {
      uploadProgress.value = 100
      props.formData.icon = response.data.url
    }
  } catch (error: any) {
    console.error('文件上传失败:', error)
    alert(`文件上传失败: ${error.message}`)
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}


// 表单验证规则
const rules = reactive<FormRules<SystemFormType>>({
  systemCode: [
    { required: true, message: '请输入系统编码', trigger: 'blur' },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: '系统编码只能包含英文和数字',
      trigger: 'blur'
    },
    { max: 20, message: '系统编码不能超过20个字符', trigger: 'blur' }
  ],
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/,
      message: '系统名称只能包含中文、英文和数字',
      trigger: 'blur'
    },
    { max: 6, message: '系统名称不能超过6个字符', trigger: 'blur' }
  ],
  systemTag: [
    { required: true, message: '请选择系统标签', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    {
      pattern: /^\d+$/,
      message: '排序只能为数字',
      trigger: 'blur'
    },
    { max: 4, message: '排序不能超过4位数字', trigger: 'blur' }
  ],
  isExternal: [
    { required: true, message: '请选择是否外链', trigger: 'change' }
  ],
  displayStatus: [
    { required: true, message: '请选择显示状态', trigger: 'change' }
  ],
  remark: [
    { max: 150, message: '备注不能超过150个字符', trigger: 'blur' }
  ]
});

// 选项数据
const options = {
  systemTags: [
    { label: '前台模块', value: 'front' },
    { label: '后台模块', value: 'back' }
  ],
  yesNoOptions: [
    { label: '是', value: 'yes' },
    { label: '否', value: 'no' }
  ],
  displayStatusOptions: [
    { label: '显示', value: 'show' },
    { label: '隐藏', value: 'hide' }
  ]
};

// 提交表单（由父组件调用）
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    emit('submit', props.formData);
  } catch (error) {
    ElMessage.error('请检查表单数据');
  }
};

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields();
  props.formData.icon = '';
  emit('reset');
};

// 暴露方法给父组件
defineExpose({
  handleSubmit,
  handleReset
});
</script>

<style scoped>
.form-section {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.form-item {
  flex: 0 0 33.33%;
  padding: 0 10px;
  margin-bottom: 15px;
}

.full-width {
  flex: 0 0 100%;
}

.icon-preview-area {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.icon-preview {
  position: relative;
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.icon-preview img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
}

.icon-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  padding: 2px;
  text-align: center;
}

.default-icon {
  width: 60px;
  height: 60px;
  background: #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  margin-right: 10px;
}
</style>